<template>
    <div class="i-table-no-border">
        <Row>
            <Col>
            <Button type="primary" icon="md-add" @click="handleOpenCreate">新建</Button>
            </Col>
            <Col class="ivu-ml-16">
            <Input placeholder="请输入唯一标识、动作行为名称、菜单名称"  v-model="keyword" v-width="300" clearable @on-enter="search" @on-clear="search"></Input>
            </Col>
        </Row>
       
      
        <Table highlight-row
               size="small"
               ref="table"
               :columns="columns"
               :data="list"
               :loading="loading"
               class="ivu-mt"
        >
            <template slot-scope="{ row }" slot="status">
                <Badge v-if="row.status === '1'" status="success" text="启用" />
                <Badge v-if="row.status === '0'" status="error" text="禁用" />
            </template>
            <template slot-scope="{ row, index }" slot="action">
                <a @click="handleUpdate(index)">编辑</a>
                <!-- <Divider type="vertical" />
        <a @click="handleDeleteItem(row)">删除</a> -->
            </template>
        </Table>
        <div class="ivu-mt ivu-text-center">
            <Page
                :total="total"
                :current.sync="current"
                show-total
                show-elevator
                :page-size="size"
                @on-change="handleChangePage"
                :page-size-opts="pageOpts"
                show-sizer
                @on-page-size-change="changePageSize"
            />
        </div>
        <Modal
            v-model="showCreate"
            :mask-closable="false"
            :title="title"
            :loading="creating"
            @on-ok="handleCreate"
        >
            <Form
                ref="create"
                :model="createMenuData"
                :rules="createRules"
                :label-width="100"
            >
                <FormItem label="动作名称：" prop="name">
                    <Input
                        v-model="createMenuData.name"
                        placeholder="请输入动作行为名称"
                        clearable
                    />
                </FormItem>
                <FormItem label="模块名称：" prop="module_id">
                    <Select
                        v-model="createMenuData.module_id"
                        style="width: 200px;"
                        @on-change="changeModule"
                    >
                        <Option
                            v-for="item in module_list"
                            :value="item.id"
                            :key="item.id"
                        >{{ item.name }}</Option
                        >
                    </Select>
                </FormItem>
                <FormItem label="菜单名称：" prop="menu_id">
                    <TreeSelect
                        v-model="createMenuData.menu_id"
                        :data="parentMenuList"
                        v-width="200"
                        :placeholder="placeholder"
                        clearable
                    />
                </FormItem>
                <FormItem label="动作路由：" prop="flag">
                    <Input
                        v-model="createMenuData.flag"
                        placeholder="请输入路由"
                        clearable
                    />
                </FormItem>
                <FormItem label="排序：" prop="sort">
                    <Input v-model="createMenuData.sort" />
                </FormItem>
                <FormItem label="菜单状态：">
                    <Switch v-model="createMenuData.status" size="large">
                        <span slot="open">开启</span>
                        <span slot="close">关闭</span>
                    </Switch>
                </FormItem>
            </Form>
        </Modal>
    </div>
</template>
<script>
import {
  GetAction,
  DetailAction,
  CreateAction,
  UpdateAction,
  DeleteAction,
} from '@/api/TApi/index.js';
export default {
  watch: {
    createMenuData(value) {
      if (value.module_id !== '') {
        this.placeholder = '请选择';
      }
    },
  },
  data() {
    return {
        keyword: '',
        columns: [
            {
            title: '唯一标识',
            key: 'marking',
            minWidth: 160,
            },
            {
            title: '动作行为名称',
            key: 'name',
            minWidth: 100,
            },
            {
            title: '菜单名称',
            key: 'menu_name',
            minWidth: 100,
            },
            {
            title: '模块名称',
            key: 'module_name',
            width: 100,
            },
            {
            title: '排序',
            key: 'sort',
            width: 80,
            },
            {
            title: '状态',
            slot: 'status',
            width: 100,
            },
            {
            title: '创建时间',
            key: 'created_at_str',
            minWidth: 100,
            },
            {
            title: '操作',
            slot: 'action',
            align: 'center',
            width: 100,
            },
        ],
        loading: false,
        list: [],
        placeholder: '请先选择模块',
        parentMenuList: [],
        parentMenuListAll: {},
        module_list: [],
        pageOpts: [10, 20, 30, 50],
        current: 1,
        size: 10,
        total: 0,
        showCreate: false,
        createMenuData: {
            name: '',
            flag: '',
            module_id: '',
            menu_id: '',
            status: true,
            sort: '',
        },
        createRules: {
            name: [
            {
                required: true,
                message: '请输入动作行为名称',
                trigger: 'blur',
            },
            ],
            sort: [
            {
                message: '排序必须是正数字',
                pattern: /^[+]{0,1}(\d+)$/,
                trigger: 'blur',
            },
            ],
            menu_id: [{ required: true, message: '请选择菜单', trigger: 'blur' }],
            module_id: [{ required: true, message: '请选择模块', trigger: 'blur' }],
            flag: [{ required: true, message: '请输入路由', trigger: 'blur' }],
            status: [
            {
                required: true,
                message: '请输入动作行为状态',
                trigger: 'blur',
            },
            ],
        },
        creating: true,
        updateIndex: -1,
        editing: true,
        title: '新增',
        };
  },
  methods: {
    search(){
        this.getData();
    },
    changeModule() {
      this.parentMenuList = [];
      let id = this.createMenuData.module_id;
      if (id && this.parentMenuListAll[id]) {
        this.parentMenuList = this.filterArr(this.parentMenuListAll[id], id);
        this.placeholder = '请选择';
      } else {
        this.parentMenuList = [];
        this.placeholder = '该模块下暂无可选菜单';
      }
    },
    filterArr(arr, id) {
      arr.forEach((ee) => {
        if (ee.children && !(ee.children instanceof Array)) {
          ee.children = [...ee.children[id]];
          this.filterArr(ee.children);
        } else {
          return false;
        }
      });
      return arr;
    },
    getData() {
      this.loading = true;
      GetAction({
        keyword: this.keyword,
        pageSize: this.size,
        page: this.current,
      })
        .then((res) => {
          this.list = res.list;
          this.total = res.total;
        })
        .finally(() => {
          this.loading = false;
        });
    },
    // 获取父级菜单
    getParentMenuList(id) {
      DetailAction({ id: id }).then((res) => {
        this.parentMenuListAll = res.menu_list;
        this.module_list = res.module_list;
        if (id !== 0) {
          let id = this.createMenuData.module_id;
          this.parentMenuList = this.filterArr(this.parentMenuListAll[id], id);
        }
      });
    },
    handleSelectModule(value) {
      // 选中动作行为
      if (!value) return false;
      this.getParentMenuList(value);
    },
    // 点击切换分页
    handleChangePage(currentPage) {
      this.current = currentPage;
      this.getData();
    },
    changePageSize(e) {
      this.size = e;
      this.getData();
    },
    handleClickItem(name) {},
    // 点击新增
    handleOpenCreate() {
      this.updateIndex = -1;
      this.showCreate = true;
      this.title = '新增';
      this.getParentMenuList(0);
      this.$nextTick(() => {
        this.$refs['create'].resetFields();
        this.$nextTick(() => {
          this.placeholder = '请先选择模块';
        });
      });
    },
    // 新增数据
    handleCreate() {
      this.$refs.create.validate((valid) => {
        if (valid) {
          let sendData = JSON.parse(JSON.stringify(this.createMenuData));
          sendData.status = sendData.status === true ? '1' : '0';
          if (this.updateIndex < 0) {
            // 新建
            CreateAction(sendData).then((res) => {
              // 创建动作行为成功后，刷新页面
              this.showCreate = false;
              this.getData();
              this.$Message.success('创建动作行为成功');
            });
          } else {
            // 修改
            UpdateAction(sendData).then((res) => {
              // 修改动作行为成功后，刷新页面
              this.showCreate = false;
              this.getData();
              this.$Message.success('修改成功');
            });
          }
          this.creating = false;
          this.$nextTick(() => {
            this.creating = true;
          });
        } else {
          this.creating = false;
          this.$nextTick(() => {
            this.creating = true;
          });
        }
      });
    },
    // 删除动作行为
    handleDeleteItem(row) {
      this.$Modal.confirm({
        title: '警告',
        content: '是否确认删除该动作行为',
        onOk: () => {
          DeleteAction({
            id: row.id,
          }).then((res) => {
            if (this.list.length === 1) this.current--;
            this.getData();
            this.$Message.success('删除成功');
          });
        },
      });
    },
    // 编辑数据
    handleUpdate(index) {
      this.showCreate = true;
      this.title = '编辑';
      this.$nextTick(() => {
        this.$refs['create'].resetFields();
        this.updateIndex = index;
        const item = this.list[index];
        this.getParentMenuList(item.id);
        for (let key in this.createMenuData) {
          this.createMenuData[key] = item[key];
        }
        this.createMenuData.status = this.createMenuData.status === '1';
        this.createMenuData.id = item.id;
      });
    },
  },
};
</script>
